﻿using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom;
using System.Runtime.InteropServices;
using Keel;

namespace KeelKit.Generators
{
    public class StructModelGengerator : ModelGengerator 
    {

        CodeTypeDeclaration ctst;
        public StructModelGengerator(string cfNameSpace, string cfClassName)
            : base(cfClassName, cfClassName)
        {
            ctst=new CodeTypeDeclaration("struct_"+cfClassName);
            ctst.IsStruct =true ;
            ctst.CustomAttributes.Add(new CodeAttributeDeclaration(
                new CodeTypeReference(typeof(StructLayoutAttribute))
                , new CodeAttributeArgument(new CodePrimitiveExpression(LayoutKind.Sequential))
                , new CodeAttributeArgument("CharSet", new CodePrimitiveExpression(CharSet.Ansi))));

            cns.Types.Add(ctst);
        }
        public static new void GeneratedCode()
        {
            Common.ShowInfo("正在检查数据库是否可用!");
            if (Kit.CheckDataBase())
            {
                EnvDTE.Project pjt;
                List<SQLTableInfo> dbix;
                string[] lsttab;
                GenReadyInfos(out pjt, out dbix, out lsttab);
                foreach (var item in lsttab)
                {
                    List<SQLTableInfo> lstdb = GenReadyItemInfos(dbix, item);
                    StructModelGengerator mg = new StructModelGengerator((string)pjt.Properties.Item("RootNamespace").Value, item);
                    foreach (var tableitem in lstdb)
                    {
                        mg.AddProperty(tableitem);
                    }
                    SaveProject(pjt, mg);
                }
                Common.ShowInfo(string.Format("全部实体生成完毕!"));


            }
        }

       public new  bool AddProperty(string name, Type type, System.CodeDom.CodeAttributeDeclaration cad)
       {
           bool i = false;
           try
           {
               CodeMemberField cmf = new CodeMemberField(type, "_" + name);
               CodeMemberProperty cmp = new CodeMemberProperty();
               cmp.Name = name;
               cmp.CustomAttributes.Add(cad);
               cmp.Type = new CodeTypeReference(type);
               cmp.Attributes = MemberAttributes.Public;
               cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + name)));
               cmp.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + name), new CodePropertySetValueReferenceExpression()));
               ctd.Members.Add(cmf);
               ctd.Members.Add(cmp);
               i = true;
           }
           catch (Exception)
           {
               i = false;
           }
           return i;
       }
    }
}
